<template>
  <div class="login">
    <el-form
      :model="form"
      status-icon
      :rules="rules"
      ref="form"
      label-width="80px"
      class="login-form"
    >
      <h2 class="login-title">登录</h2>
      <el-form-item label="账号" prop="username">
        <el-input
          type="text"
          v-model="form.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" style="margin: 0">
        <el-input
          type="password"
          v-model="form.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item style="margin-bottom: 0" class="left" prop="check">
        <el-checkbox
          label="记住登录"
          name="type"
          v-model="form.check"
        ></el-checkbox>
      </el-form-item>
      <el-form-item class="login-button">
        <el-button
          style="float: left; margin-left: -50px"
          type="primary"
          @click="onSubmit('form')"
          >登录
        </el-button>
        <el-button
          style="float: left; margin-left: 40px"
          type="primary"
          @click="onEnroll"
          >注册</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 弹窗 -->
    <el-dialog title="注册用户" :visible.sync="dialogFormVisible" width="400px">
      <el-form
        :model="enroll"
        status-icon
        ref="enroll"
        label-width="100px"
        label-position="left"
        style="width: 90%"
        :rules="rules"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input
            v-model="enroll.username"
            placehilder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" type="password">
          <el-input
            v-model="enroll.password"
            placehilder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="enroll.name" placehilder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="enroll.phone"
            placehilder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="校验码" prop="encrypt">
          <el-input
            v-model="enroll.encrypt"
            placehilder="请输入管理员校验码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addData('enroll')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import loginApi from "@/api/login";
import memoryUtils from "@/utils/memoryUtils";
import storageUtils from "@/utils/storageUtils";
import rolesApi from "@/api/roles";
export default {
  data() {
    var validateUserName = (rule, value, callback) => {
      value = value.trim();
      const length = value && value.length;
      const pwdReg = /^[a-zA-Z0-9_]+$/;
      if (value === "") {
        callback(new Error("请输入账号"));
      } else if (length < 4 || length > 12) {
        callback(new Error("长度在4-12个字符之间"));
      } else if (!pwdReg.test(value)) {
        callback(new Error("账号格式为英文数字或下划线组成"));
      } else {
        callback();
      }
    };
    return {
      user: {},
      enroll: {
        username: "",
        password: "",
        check: false,
        encrypt: "",
        name: "",
        phone: "",
      },
      form: {
        username: "",
        password: "",
        check: false,
      },
      dialogFormVisible: false,
      rules: {
        username: [
          {
            required: true,
            validator: validateUserName,
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"],
          },
        ],
        encrypt: [{ required: true, message: "必输项" }],
      },
    };
  },

  components: {},
  methods: {
    // 需求：注册
    // 前端出现弹窗；弹窗内容包括用户名密码和验证码
    // 后端：调用user数据库存储，先判断user是否存在不存在在添加存在则返回提示信息
    // 注册
    onEnroll() {
      this.dialogFormVisible = true;
      // 异步事件
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
        this.$refs["enroll"].resetFields();
      });
    },
    // 注册
    addData(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let result = await loginApi.enroll(this.enroll);
          result = result.data;
          if (result.status == 0) {
            this.$message({
              message: "注册成功",
              type: "success",
            });
            console.log(result);
            const user = result.data;
            console.log(user);
            // ============================
            const roleMenus = await rolesApi.loginRole(user.role_id);
            console.log(result);
            // console.log(res.data);
            memoryUtils.user = user;
            memoryUtils.user.menus = roleMenus.data.data.menus;
            memoryUtils.user.check = this.form.check;
            // 将数据存入user中
            this.user = memoryUtils.user;
            // console.log(this.user);
            this.$store.commit("ADD_USER", this.user);
            // =========================
            memoryUtils.user = result.data;
            this.$router.replace("/");
            // 判断是否选中按钮如果未选中将本地存储数据移除
            if (!this.form.check) {
              sessionStorage.setItem("USE_KEY", JSON.stringify(this.user));
            } else {
              storageUtils.saveUser(this.user);
            }
          } else {
            this.$message({
              message: result.msg,
              type: "warning",
            });
          }
        }
      });
    },
    // 登录
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          loginApi
            .login(this.form.username, this.form.password)
            .then(async (response) => {
              const res = response.data;
              if (res.status == 0) {
                this.$message({
                  message: "登陆成功",
                  type: "success",
                });
                const result = await rolesApi.loginRole(res.data.role_id);
                console.log(result);
                // console.log(res.data);
                const user = res.data;
                memoryUtils.user = user;
                memoryUtils.user.menus = result.data.data.menus;
                memoryUtils.user.check = this.form.check;
                // 将数据存入user中
                this.user = memoryUtils.user;
                // console.log(this.user);
                this.$store.commit("ADD_USER", this.user);
                console.log(this.$store.state);
                if (!this.form.check) {
                  sessionStorage.setItem("USE_KEY", JSON.stringify(this.user));
                } else {
                  storageUtils.saveUser(this.user);
                }
                // console.log(memoryUtils.user);
                this.$router.replace("/home");
                // 判断是否选中按钮如果未选中将本地存储数据移除
              } else {
                this.$message({
                  message: result.msg,
                  type: "warning",
                });
              }
            });
        } else {
          this.$message({
            message: result.msg,
            type: "success",
          });
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.login {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url("../../assets/login.jpeg") no-repeat;
  background-size: cover;
  overflow: hidden;
}
.login-form {
  width: 350px;
  height: 250px;
  margin: 255px auto;
  background-color: rgba(255, 255, 255, 0.5);
  padding: 18px;
  border-radius: 20px;
}
.login-title {
  text-align: center;
}
.el-input {
  width: 200px;
}
.left {
  float: right;
  margin-right: 70px;
}
.login-button {
  clear: both;
  margin: 0 60px;
}
</style>